<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>成绩管理</title>
    <link rel="stylesheet" href="../../static/layui/css/layui.css">
</head>
<body>
    <div class="layui-container">
        <div class="layui-row" style="margin-top: 20px;">
            <div class="layui-col-md12">
                <button class="layui-btn" id="addGrade">添加成绩</button>
                <table id="gradeTable" lay-filter="gradeTable"></table>
            </div>
        </div>
    </div>

    <!-- 添加成绩弹窗 -->
    <script type="text/html" id="addGradeForm">
        <form class="layui-form" style="margin: 20px;" lay-filter="addGradeForm">
            <div class="layui-form-item">
                <label class="layui-form-label">学生</label>
                <div class="layui-input-block">
                    <select name="userId" lay-verify="required" id="addUserSelect">
                        <option value="">请选择学生</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">课程</label>
                <div class="layui-input-block">
                    <select name="courseId" lay-verify="required" id="addCourseSelect">
                        <option value="">请选择课程</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">成绩</label>
                <div class="layui-input-block">
                    <input type="text" name="score" required lay-verify="required|number" placeholder="请输入成绩" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="addGradeSubmit">保存</button>
                </div>
            </div>
        </form>
    </script>

    <!-- 编辑成绩弹窗 -->
    <script type="text/html" id="editGradeForm">
        <form class="layui-form" style="margin: 20px;" lay-filter="editGradeForm">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">学生</label>
                <div class="layui-input-block">
                    <input type="text" name="userName" readonly class="layui-input" id="editUserName">
                    <input type="hidden" name="userId" id="editUserId">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">课程</label>
                <div class="layui-input-block">
                    <input type="text" name="courseName" readonly class="layui-input" id="editCourseName">
                    <input type="hidden" name="courseId" id="editCourseId">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">成绩</label>
                <div class="layui-input-block">
                    <input type="text" name="score" required lay-verify="required|number" placeholder="请输入成绩" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="editGradeSubmit">保存</button>
                </div>
            </div>
        </form>
    </script>

    <!-- 表格操作按钮 -->
    <script type="text/html" id="tableBar">
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
            <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</button>
        </div>
    </script>

    <script src="../../static/layui/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function(){
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            
            // 设置全局 Ajax 默认值
            $.ajaxSetup({
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true
            });
            
            // 初始化表格
            table.render({
                elem: '#gradeTable',
                url: 'http://localhost:8050/api/backend/grade/list',
                headers: {
                    'Content-Type': 'application/json'
                },
                xhrFields: {
                    withCredentials: true
                },
                parseData: function(res) {
                    return {
                        "code": 0,
                        "msg": res.message,
                        "count": res.data ? res.data.length : 0,
                        "data": res.data || []
                    };
                },
                cols: [[
                    {field: 'userId', title: '学生ID', width: 100},
                    {field: 'code', title: '学号', width: 120},
                    {field: 'userName', title: '学生姓名', width: 150},
                    {field: 'courseName', title: '课程名称'},
                    {field: 'score', title: '成绩', width: 100},
                    {field: 'createTime', title: '创建时间', templet: function(d){
                        return d.createTime ? d.createTime.split('T')[0] + ' ' + d.createTime.split('T')[1] : '';
                    }},
                    {fixed: 'right', title: '操作', toolbar: '#tableBar', width: 150}
                ]]
            });
            
            // 加载学生列表
            function loadUsers(selectId){
                $.get('http://localhost:8050/api/backend/user/studentList', function(res){
                    if(res.code === 200){
                        var html = '<option value="">请选择学生</option>';
                        res.data.forEach(function(user){
                            html += '<option value="' + user.id + '">' + user.userName + '</option>';
                        });
                        $('#' + selectId).html(html);
                        form.render('select');
                    }
                });
            }
            
            // 加载课程列表
            function loadCourses(selectId){
                $.get('http://localhost:8050/api/backend/course/list', function(res){
                    if(res.code === 200){
                        var html = '<option value="">请选择课程</option>';
                        res.data.forEach(function(course){
                            html += '<option value="' + course.id + '">' + course.courseName + '</option>';
                        });
                        $('#' + selectId).html(html);
                        form.render('select');
                    }
                });
            }
            
            // 添加成绩按钮点击事件
            $('#addGrade').on('click', function(){
                layer.open({
                    type: 1,
                    title: '添加成绩',
                    content: $('#addGradeForm').html(),
                    area: ['500px', '400px'],
                    success: function(){
                        loadUsers('addUserSelect');
                        loadCourses('addCourseSelect');
                    }
                });
            });
            
            // 表格工具条事件
            table.on('tool(gradeTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'edit'){
                    layer.open({
                        type: 1,
                        title: '编辑成绩',
                        content: $('#editGradeForm').html(),
                        area: ['500px', '400px'],
                        success: function(layero, index){
                            // 设置表单值
                            setTimeout(function(){
                                form.val('editGradeForm', {
                                    "id": data.id,
                                    "userId": data.userId,
                                    "courseId": data.courseId,
                                    "score": data.score
                                });
                                // 设置学生姓名和课程名称为只读文本
                                $('#editUserName').val(data.userName);
                                $('#editUserId').val(data.userId);
                                $('#editCourseName').val(data.courseName);
                                $('#editCourseId').val(data.courseId);
                                
                                form.render();
                            }, 300);
                        }
                    });
                } else if(obj.event === 'del'){
                    layer.confirm('确定要删除该成绩记录吗？', function(index){
                        $.ajax({
                            url: 'http://localhost:8050/api/backend/grade/delete',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({id: data.id}),
                            success: function(res){
                                if(res.code === 200){
                                    layer.msg('删除成功');
                                    obj.del(); // 删除对应行
                                    layer.close(index);
                                }else{
                                    layer.msg(res.message || '删除失败');
                                }
                            },
                            error: function(){
                                layer.msg('服务器错误，请稍后重试');
                            }
                        });
                    });
                }
            });
            
            // 添加成绩表单提交事件
            form.on('submit(addGradeSubmit)', function(data){
                $.ajax({
                    url: 'http://localhost:8050/api/backend/grade/add',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    success: function(res){
                        if(res.code === 200){
                            layer.msg('添加成功');
                            layer.closeAll('page');
                            table.reload('gradeTable');
                        }else{
                            layer.msg(res.message);
                        }
                    }
                });
                return false;
            });
            
            // 编辑成绩表单提交事件
            form.on('submit(editGradeSubmit)', function(data){
                var formData = data.field;
                // 构建要提交的数据对象
                var submitData = {
                    id: formData.id,
                    userId: formData.userId,
                    courseId: formData.courseId,
                    score: formData.score
                };
                
                $.ajax({
                    url: 'http://localhost:8050/api/backend/grade/edit',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function(res){
                        if(res.code === 200){
                            layer.msg('修改成功');
                            layer.closeAll('page');
                            // 刷新表格数据
                            table.reload('gradeTable');
                        }else{
                            layer.msg(res.message || '修改失败');
                        }
                    },
                    error: function(){
                        layer.msg('服务器错误，请稍后重试');
                    }
                });
                return false;
            });
        });
    </script>
</body>
</html> 